package com.code.exam.controller;


import com.code.exam.annotation.LoginCheck;
import com.code.exam.common.content.BaseContext;
import com.code.exam.common.properties.JwtProperties;
import com.code.exam.common.result.Result;
import com.code.exam.common.utils.JwtUtil;
import com.code.exam.dto.AdminLoginDTO;
import com.code.exam.dto.AdminRegisterDTO;
import com.code.exam.dto.CgPasswordDTO;
import com.code.exam.entity.Admin;
import com.code.exam.service.AdminService;
import com.code.exam.vo.AdminLoginVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/login")
    @ApiOperation("管理员登入")
    public Result<AdminLoginVO> login(@RequestBody AdminLoginDTO adminLoginDTO) {
        log.info("管理员登录{}", adminLoginDTO);
        Admin admin  = adminService.login(adminLoginDTO);

        //登录成功生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("adminId", admin.getId());
        claims.put("role", "ADMIN");
        String jwt = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),claims);


        AdminLoginVO adminLoginVO = AdminLoginVO.builder()
                .id(admin.getId())
                .username(admin.getUsername())
                .token(jwt)
                .build();

        return Result.success(adminLoginVO);
    }

    @PostMapping("/register")
    public Result register(@RequestBody AdminRegisterDTO adminRegisterDTO){

        log.info("管理员注册{}",adminRegisterDTO);
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminRegisterDTO,admin);
        String adminName = adminService.register(admin);
        return Result.success(adminName);
    }


    @LoginCheck(role = "admin")
    @PostMapping("/changepassword")
    @ApiOperation("管理员修改密码")
    public Result changepassword(@RequestBody CgPasswordDTO cgPasswordDTO){
        log.info("管理员修改密码{}",cgPasswordDTO);
        //校验数据是否为空
        if(cgPasswordDTO.getOldPassword() == null ||
                cgPasswordDTO.getNewPassword() == null)
        {
            return Result.error("旧密码和新密码不能为空");
        }
        Long adminId = BaseContext.getCurrentId();
        adminService.changepassword(adminId,cgPasswordDTO);
        return Result.success("密码修改成功");

    }







}
